import httpConfig from '@/config/http';
import cacheConfig from '@/config/cache.js';

const request = (apiConfig = {url: '',method: '',data: {}}) => {
	const options = {url: '',header: {}, method: '', data: {}, success: () => {}, fail: () => {}};
	options.url = httpConfig.BASE_URL + apiConfig.url;
	options.header = httpConfig.HEADER;
	if(cacheConfig.GET_TOKEN()) options.header[httpConfig.TOKEN_NAME] = cacheConfig.GET_TOKEN();
	options.method = apiConfig.method ? apiConfig.method : httpConfig.METHODS.GET;
	if(!apiConfig.method) console.error(`api/index.js: 该${apiConfig.url}请求缺失请求方法, 已默认为GET发起请求`);
	if(apiConfig.data && typeof apiConfig.data != 'object') console.error(`api/index.js: 该${apiConfig.url}请求的参数类型为${typeof apiConfig.data}不是对象, 请将参数包装在对象中`);
	options.data = apiConfig.data ? apiConfig.data : {};
	
	return new Promise((resolved, rejected) => {
		options.success = res => {
			if(res.data.code == 200 || res.data.code == 400 || res.data.code == 500) resolved(res.data);
			if (res.data.code == 403) {
				// uni.showToast({ icon: 'none', duration: 3000, title: `${res.data.message}`});
				// 登陆失效
				uni.showToast({ icon: 'none', duration: 3000, title: '登陆已过期, 请重新登录'});
				cacheConfig.clearToken();
				rejected(res.data);
				// uni.reLaunch(url: '/pages/login/login')
			}
		}
		options.fail = err => {
			// 请求失败弹窗
			uni.showToast({ icon: 'none', duration: 3000, title: '网络信号差, 请稍后再试'});
			rejected(err);
		};
		uni.request(options);
	});
}

export default request;